package pro.jiug.kWord.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.junit.Test;
import pro.jiug.kWord.entity.Student;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class WordController {
    @Test
    public void test(){
        Map<String,Object> dataMap = new HashMap<String, Object>();
        try {
            //年级
            dataMap.put("grade", "高三");
            //班级
            dataMap.put("class", "8班");
            //成绩集合
            dataMap.put("studentList", getStudentList());

            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("utf-8");

            //指定路径的第一种方式（根据某个类的相对路径指定）
            configuration.setClassForTemplateLoading(this.getClass(), "/templates");

            //输出文档路径及名称
            File outFile = new File("D:/成绩单.doc");

            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("word.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<Student> getStudentList(){
        List<Student> studentList=new ArrayList<>();
        studentList.add(new Student("曹操",100,78));
        studentList.add(new Student("刘备",89,90));
        studentList.add(new Student("孙权",90,85));
        studentList.add(new Student("袁绍",82,63));
        studentList.add(new Student("周瑜",92,95));
        studentList.add(new Student("诸葛亮",99,98));

        for (int i = 1; i <=studentList.size() ; i++) {
            studentList.get(i-1).setId(i);
        }

        //排序规则 sum->chinese->math->name
        Collections.sort(studentList,
                (s1,s2) -> s1.getSum()-s2.getSum()!=0? s1.getSum()-s2.getSum():
                        s1.getChinese()-s2.getChinese()!=0? s1.getChinese()-s2.getChinese():
                                s1.getMath()-s2.getMath()!=0?s1.getMath()-s2.getMath():
                                        s1.getName().compareTo(s2.getName())
                );
        return studentList;

    }


}
